package app.base.systemmanage.systemmenusmanage;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataIntegrityViolationException;

import app.base.common.Utility;

import app.base.systemmanage.systemmenusmanage.dao.SysMenusDAO;
import app.base.systemmanage.systemmenusmanage.model.SysMenus;
import app.base.systemmanage.systempermsmanage.dao.SysPermissionsDAO;
import app.base.systemmanage.systempermsmanage.model.SysPermissions;
import app.base.systemmanage.systempermsmanage.model.SysPermissionsExample;
import app.base.systemmanage.systempermsmanage.model.SysPermissionsExample.Criteria;

public class SystemMenusHandle extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
		
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
	    request.setCharacterEncoding(Utility.CHARSET_ENCODING_UTF8);
	    response.setContentType(Utility.DEFAULT_CONTENT_TYPE);

		PrintWriter out = response.getWriter(); 
						
		String cmd = request.getParameter("SYSTEM_MENUS_OPERATION_COMMAND").trim();
		String result = null;

		if (cmd == null)
		{
			result = "{returnCode: '-1', msg: '客户端的数据请求命令参数CMD为NULL'}";
		}
		else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_ADD) || cmd.equals(Utility.SYS_OPERATION_COMMAND_MODIFY))
		{
			SysMenus record = new SysMenus();
						
			record.setMENU_ID(URLDecoder.decode(request.getParameter("MENU_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setMENU_PARENT_ID(URLDecoder.decode(request.getParameter("MENU_PARENT_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setMENU_NAME(URLDecoder.decode(request.getParameter("MENU_NAME").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setMENU_DESC(URLDecoder.decode(request.getParameter("MENU_DESC").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setMENU_NAV_URL(URLDecoder.decode(request.getParameter("MENU_NAV_URL").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setNORMAL_IMG_URL(URLDecoder.decode(request.getParameter("NORMAL_IMG_URL").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setEXPAND_IMG_URL(URLDecoder.decode(request.getParameter("EXPAND_IMG_URL").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setLEAF_NODE_FLAG(request.getParameter("LEAF_NODE_FLAG").trim());
			record.setDISPLAY_RANKING_INDEX( BigDecimal.valueOf(Integer.valueOf(request.getParameter("DISPLAY_RANK_INDEX").trim())));
			record.setMENU_DISPLAY_FLAG(request.getParameter("MENU_DISPLAY_FLAG").trim());
			record.setSYS_HOLD_FLAG(request.getParameter("SYS_HOLD_FLAG").trim());

			result = doSystemOperations(cmd, record);
		}
		else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_DELETE))
		{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("MENU_ID", URLDecoder.decode(request.getParameter("MENU_ID").trim(), Utility.CHARSET_ENCODING_UTF8));

			result = doSystemOperations(cmd, map);
		}
		else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_GENERATE))
		{
			result = doSystemOperations(cmd, null);
		}
		else
		{
			result = "{returnCode: '-1', msg: '服务器不支持的数据请求命令，请检查后再重试'}";
		}
		
		out.println(result);
		
		out.flush();
		out.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
		doGet(request, response);
	}
	
	@SuppressWarnings("unchecked")
	private String doSystemOperations(String action, Object o)
	{
		
		String result = "{returnCode: '-1', msg: '系统调用函数 doSysMenusOperation() 失败'}";
		
		ApplicationContext context = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysMenusDAO sysMenusDAO = (SysMenusDAO)context.getBean(Utility.SYSTEM_MENUS_MANAGE_MODULE_BEAN_NAME);
		
		if (action.equals(Utility.SYS_OPERATION_COMMAND_ADD))
		{
			result = insert(sysMenusDAO, (SysMenus) o);
		}
		else if (action.equals(Utility.SYS_OPERATION_COMMAND_MODIFY))
		{
			result = update(sysMenusDAO, (SysMenus) o);
		}
		else if (action.equals(Utility.SYS_OPERATION_COMMAND_DELETE))
		{			
			result = delete(sysMenusDAO, (Map<String, Object>) o);			
		}
		else if (action.equals(Utility.SYS_OPERATION_COMMAND_GENERATE))
		{			
			result = generateMenusPerms();			
		}
		
		return result;
	}
	
	private String insert(SysMenusDAO sysMenusDAO, SysMenus record)
	{
		String result = "{returnCode: '0', msg: '新增系统菜单项成功'}";
		
		try {
			sysMenusDAO.insert_0001(record);		
		} 
		catch(DataIntegrityViolationException e)
		{
			result = "{returnCode: '-1', msg: '系统不允许创建重复的菜单项'}";
		}
		catch (Exception e) {
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}

	private String update(SysMenusDAO sysMenusDAO, SysMenus record)
	{
		String result = "{returnCode: '0', msg: '修改系统菜单项成功'}";
		
		try {
			sysMenusDAO.update_0001(record);		
		} 		
		catch(DataIntegrityViolationException e)
		{
			result = "{returnCode: '-1', msg: '系统不允许在同一菜单项下创建相同名称的多个菜单项'}";
		}
		catch (Exception e) {
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}
	
	private String delete(SysMenusDAO sysMenusDAO, Map<String, Object> map)
	{
		String result = "{returnCode: '0', msg: '删除系统菜单项成功'}";
		
		try {
			sysMenusDAO.delete_0001(map);		
		} catch (Exception e) {
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}	

	@SuppressWarnings("unchecked")
	private String generateMenusPerms()
	{
		String result = "{returnCode: '0', msg: '更新系统菜单权限成功'}";
		
		//
		ApplicationContext sysMenusContext = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysMenusDAO sysMenusDAO = (SysMenusDAO)sysMenusContext.getBean(Utility.SYSTEM_MENUS_MANAGE_MODULE_BEAN_NAME);
		
		ApplicationContext sysPermissionsContext = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysPermissionsDAO sysPermissionsDAO = (SysPermissionsDAO)sysPermissionsContext.getBean(Utility.SYSTEM_PERMISSIONS_MANAGE_MODULE_BEAN_NAME);
		
		//
		String permXtypeName = "菜单权限(系统手动生成)";
		String normalImgUrl = "resources/images/plugin.gif";
		
		//
		Map<String, Object>  map = new HashMap<String, Object>();
		
		map.put("permXtypeName", permXtypeName);
		
		List sysPermissionsList = sysPermissionsDAO.select_0003(map);
		
		if (sysPermissionsList.size() == 1)
		{	
			String permXtypeId = ((Map) sysPermissionsList.get(0)).get("PERM_XTYPE_ID").toString().trim();

			try {
				sysPermissionsDAO.getMySqlMapClient().startTransaction();
				
				//
				SysPermissionsExample example = new SysPermissionsExample();
				
				Criteria criteria = example.createCriteria();
				
				criteria.andPERM_XTYPE_PARENT_IDEqualTo(permXtypeId);
				
				sysPermissionsDAO.deleteByExample(example);
				
				//
				List<SysMenus> list = sysMenusDAO.select_0002(null);
				
				for(int index = 0; index < list.size(); index++){
					SysMenus sysMenus = (SysMenus) list.get(index);
					
					String menuId = sysMenus.getMENU_ID().trim();
					String menuName = sysMenus.getMENU_NAME().trim();
					
					//
					SysPermissions record = new SysPermissions();
		
					record.setPERM_XTYPE_PARENT_ID(permXtypeId);
					record.setPERM_XTYPE_NAME(menuName + "-" + menuId);
					record.setPERM_CODE(menuId);
					record.setPERM_XTYPE_DESC(menuName);
					record.setNORMAL_IMG_URL(normalImgUrl);
					record.setLEAF_NODE_FLAG("1");
					record.setDISPLAY_RANKING_INDEX(BigDecimal.valueOf(0));
					record.setSYS_HOLD_FLAG("1");
					record.setSTATE("0");
							
					sysPermissionsDAO.insert_0001(record);
				}
				
				sysPermissionsDAO.getMySqlMapClient().commitTransaction();
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result = "{returnCode: '-1', msg: '更新系统菜单权限失败：未知错误'}";
			}
			finally{
				try {
					sysPermissionsDAO.getMySqlMapClient().endTransaction();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}		
		}
		else
		{
			result = "{returnCode: '-1', msg: '更新系统菜单权限失败：未找到\"菜单权限\"项" + sysPermissionsList.size() + "'}";
		}
		
		return result;
	}	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//SystemMenusHandle smh = new SystemMenusHandle();
		//System.out.println(smh.generateMenusPerms());
	}

}
